import { stringify } from "./utils"
import fs from '../fileio-extra/fs'
import { fromCallback, fromPromise } from "../universalify"

function _readFile(file, options) {
  return new Promise((res, rej) => {
    if (typeof options === 'string') {
      options = {
        encoding: options
      }
    }
    const shouldThrow = "throws" in options ? options.throws : true;
    fs.readText(file, options, (err, data) => {
      let obj
      try {
        obj = JSON.parse(data, options ? options.reviver : null)
      } catch (err) {
        if (shouldThrow) {
          err.message = `${file}:${err.message}`
          throw err
        } else {
          res(null)
        }
      }
      res(obj)
    })
  })
}

const readFile = fromPromise(_readFile)

function readFileSync(file, options) {
  if (typeof options === 'string') {
    options = { encoding: options }
  }
  const shouldThrow = 'throws' in options ? options.throws : true
  try {
    let content = fs.readTextSync(file, options)
    return JSON.parse(content, options.reviver)
  } catch (err) {
    if (shouldThrow) {
      err.message = `${file}:${err.message}`
      throw err
    } else {
      return null
    }
  }
}

function _writeFile(file, obj, options={}) {
  return new Promise((res, rej) => {
    const str = stringify(obj, options)
    res(fromCallback(fs.writeFile)(file, str, options))
  })
}

const writeFile = fromPromise(_writeFile)

function writeFileSync(file, obj, options={}) {
  const str = stringify(obj, options)
  //not sure if fs.writeFileSync returns anything,but just in case
  return fs.writeFileSync(file, str, options)
}

export default {
  readFile,
  readFileSync,
  writeFile,
  writeFileSync
}